package com.ywz.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.project.base.system.entity.TSysLoginLog;
import com.ywz.project.base.system.service.TSysLoginLogService;
import com.ywz.project.system.dto.req.LoginLogPageReq;
import com.ywz.project.system.service.LoginLogApiService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoginLogApiServiceImpl implements LoginLogApiService {
    @Resource
    private TSysLoginLogService sysLoginLogService;

    @Override
    public ResultResp getLoginLogPage(LoginLogPageReq req) {
        LambdaQueryWrapper<TSysLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysLoginLog::getIsDeleted, 0);
        if (!StringUtils.isEmpty(req.getUser()))
            queryWrapper.like(TSysLoginLog::getUserName, req.getUser());
        if (StringUtils.isDate(req.getStartTime()))
            queryWrapper.ge(TSysLoginLog::getCreatedTime, req.getStartTime());
        if (StringUtils.isDate(req.getEndTime()))
            queryWrapper.le(TSysLoginLog::getCreatedTime, req.getEndTime());
        queryWrapper.orderByDesc(TSysLoginLog::getCreatedTime);
        Page<TSysLoginLog> page = new Page<>(req.getPageNum(), req.getPageSize());
        return ResultResp.success(sysLoginLogService.page(page, queryWrapper));
    }

    @Override
    public ResultResp removeLoginLog(String ids) {
        if(StringUtils.isNumberAndSeparator(ids)){
            String[] split = ids.split(StringUtils.SEPARATOR);
            List<Integer> collect = Arrays.stream(split).map(Integer::parseInt).collect(Collectors.toList());
            LambdaUpdateWrapper<TSysLoginLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(TSysLoginLog::getId, collect);
            updateWrapper.set(TSysLoginLog::getIsDeleted, 1);
            updateWrapper.set(TSysLoginLog::getUpdatedTime, LocalDateTime.now());
            boolean updated = sysLoginLogService.update(updateWrapper);
            return updated ? ResultResp.success() : ResultResp.error("删除失败");
        }else{
            return ResultResp.error("参数错误");
        }
    }
}
